package com.xma.springcloud.controller;

import com.xma.springcloud.common.ResponseResult;
import com.xma.springcloud.entity.Payment;
import com.xma.springcloud.lb.LoadBalancer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;


/**
 * @Author: arthur
 * @License: (C) Copyright 2020-2028, xxx Corporation Limited.
 * @Contact: 413911174@qq.com
 * @Date: 2020/6/22 20:36
 * @Version: 1.0
 * @Description:
 */
@RestController
@RequestMapping("/consumer")
public class OrderController {

    //public static final String PAYMENT_URL = "http://localhost:8003";
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Autowired
    private RestTemplate restTemplate;

    //负载均衡
    @Resource
    private LoadBalancer loadBalancer;
    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/payment/create")
    public ResponseResult<Payment> create(Payment payment){
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create" ,payment,ResponseResult.class);
    }

    @GetMapping(value = "/payment/get/{id}")
    public ResponseResult<Payment> createPayment(@PathVariable("id") Long id){
        ResponseResult result = restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, ResponseResult.class);
        System.out.println(result.toString());
        return result;
    }
    // 轮播
    @GetMapping(value = "/payment/lb")
    public String getPaymentLB(){
        //微服务发现客户端，发现服务器注册的服务，获取服务列表。
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        if(instances == null || instances.size() <=0){
            return null;
        }

        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri + "/payment/lb",String.class);
    }

    // zipkin + sleuth

    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){
        //微服务发现客户端，发现服务器注册的服务，获取服务列表。
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        if(instances == null || instances.size() <=0){
            return null;
        }

        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        String result = restTemplate.getForObject(uri + "/payment/zipkin" ,String.class);
        return result;
    }

}
